package com.example.demo.common.api;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: csj
 * @Date: 2024/4/7 16:39
 * @Description:
 */
@ControllerAdvice
@Slf4j
public class ControllerException  {
    private final static String EXCEPTION_MSG_KEY = "Exception message : ";

    @ResponseBody
    //@ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseData handleValidException(MethodArgumentNotValidException e) {
        return ResponseData.error(ResultCodeEnum.ERROR,e.getBindingResult().getFieldError().getDefaultMessage());
    }
    @ExceptionHandler(UserException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData<Object> APIExceptionHandler(UserException ex) {
        log.error("主动抛出自定义异常！异常信息：{}",ex.getMsg());
        return  ResponseData.error(ex.getCode(),ex.getMsg());
    }

    /**
     * @Description: 方法参数错误异常
     * @Date: 2021/8/10 14:47
     * @param: ex 异常对象
     * @return: com.ieslab.validationcase.util.result.ResponseData<java.lang.Object>
     * @Version: 1.0
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData<Object> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        log.error("方法参数错误异常！异常信息：{}",ex.getMessage());
        List<String> msgList=new ArrayList<>();
        if(!ex.getBindingResult().getAllErrors().isEmpty()){
            for(ObjectError objectError:ex.getBindingResult().getAllErrors()){
                msgList.add(objectError.getDefaultMessage().toString());
            }
        }
        return  ResponseData.error(ResultCodeEnum.VALIDATE_FAILED,ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * @Description: 兜底作用
     * @Date: 2021/8/10 14:54
     * @param: ex
     * @return: com.ieslab.validationcase.util.result.ResponseData<java.lang.Object>
     * @Version: 1.0
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseData<Object> ExceptionHandler(Exception ex) {
        log.error("未知异常！异常信息：{}",ex.getMessage());
        return  ResponseData.error(ResultCodeEnum.ERROR.getCode(),ex.getMessage());
    }


}
